package plugins.detail;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.list.BillList;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.ArrayList;
import java.util.List;

public class ShouCangMerchant extends AbstractListPlugin implements Plugin {

    @Override
    public void itemClick(ItemClickEvent e) {
        super.itemClick(e);

        if ("dcb4_shoucangmerchant".equalsIgnoreCase(e.getItemKey())) {
            BillList billList = this.getControl("billlistap");
            ListSelectedRowCollection selectedRows = billList.getSelectedRows();

            if (!selectedRows.isEmpty()) {
                // 准备批量更新的单据ID集合
                List<Object> billIds = new ArrayList<>();

                // 遍历选中行收集单据ID
                for (ListSelectedRow row : selectedRows) {
                    billIds.add(row.getPrimaryKeyValue());
                }

                // 批量加载单据数据
                QFilter filter = new QFilter("id", QCP.in, billIds);
                DynamicObject[] bills = BusinessDataServiceHelper.load(
                        billList.getBillFormId(),
                        "id,dcb4_ifshoucang,billstatus",
                        new QFilter[]{filter}
                );


                // 修改字段值
                for (DynamicObject bill : bills) {
                    bill.set("dcb4_ifshoucang", "B");
                }

                // 批量保存单据
                OperationServiceHelper.executeOperate(
                        "save",
                        billList.getBillFormId(),
                        bills,
                        null
                );

                this.getView().showTipNotification("收藏成功！");

                // 刷新列表显示
                this.getView().updateView("billlistap");
            }
        }
    }
}
